<template>
    <div class="app-container">
        <el-form ref="postForm" :rules="rules" :model="postForm" label-position="left" label-width="70px" style="margin-left: 50px">
            <el-form-item label="网关" prop="gateway_id" label-width="140px">
                <el-select v-model="postForm.gateway_id">
                    <el-option v-for="(gateway, index) in gateway_list" :key="index" :label="gateway.name" :value="gateway.id">{{ gateway.name }}</el-option>
                </el-select>
            </el-form-item>
            <el-button v-loading="loading" style="margin-left: 10px;" type="primary" @click="submitForm">
                保存
            </el-button>
        </el-form>
    </div>
</template>

<script>
import { list as gatewayList } from '@/iot/api/gateway/gateway'
import { get, setGateway } from '@/iot/api/device/device'

const defaultForm = {
    gateway_id: null
}

export default {
    data() {
        const validateRequire = (rule, value, callback) => {
            if (value === '' || value === null || value === undefined) {
                this.$message({
                    message: rule.message,
                    type: 'error'
                })
                callback(new Error())
            } else {
                callback()
            }
        }
        return {
            gateway_list: [],
            postForm: Object.assign({}, defaultForm),
            loading: false,
            rules: {}
        }
    },
    created() {
        this.fetchData()
        gatewayList().then(res => {
            this.gateway_list = res.data.items
        })
    },
    methods: {
        fetchData() {
            get({
                id: this.$route.query.id
            }).then(res => {
                this.postForm.gateway_id = res.data.gateway_id
            })
        },
        submitForm() {
            this.loading = true
            const data = this.postForm
            data.id = this.$route.query.id
            setGateway(data).then(response => {
                this.$notify({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                })
                // this.postForm.status = 'published'
                this.loading = false
                this.fetchData()
                // this.$router.push('/store/index')
            }).catch(err => {
                console.log(err)
                this.loading = false
            })
        }
    }
}
</script>

<style>
</style>
